﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Rendering.Universal;

namespace Assets.Scripts
{
	public class CameraFollow : MonoBehaviour
	{
		private Transform m_transform;
		/// <summary>
		/// 初始的时候，从几何中心指向本位置
		/// </summary>
		[SerializeField]
		private Vector3 direction;

		/// <summary>
		/// 最大显示区域
		/// </summary>
		[SerializeField]
		private Vector2 MaxShowField;
		[SerializeField]
		private Vector2 MinSize;

		[SerializeField]
		private float LerpSpeed;
		[SerializeField]
		private float CameraZoomSpeed;

		private Star[] stars;
		//private GameObject[] stars;
		//private GameObject planet;

		[SerializeField]
		private Transform focusOn;

		/// <summary>
		/// 屏幕宽度除以屏幕高度
		/// </summary>
		private float screenWDivideScreenH;

		[SerializeField]
		float maxX;
		[SerializeField]
		float maxY;

		public void Start()
		{
			m_transform = GetComponent<Transform>();
			//stars = GameObject.FindGameObjectsWithTag("star");
			stars = GameObject.FindObjectsOfType<Star>();
			//planet = GameObject.FindGameObjectWithTag("planet");


			//Vector3 temp = FindWeightCore();
			Vector3 temp = focusOn.position;
			direction = m_transform.position - temp;
			direction.x = direction.y = 0;

			screenWDivideScreenH = Camera.main.pixelWidth * 1f / Camera.main.pixelHeight;
		}

		private void FixedUpdate()
		{
			Vector3 target = focusOn.position;
			m_transform.position = Vector3.Lerp(m_transform.position, target + direction, LerpSpeed);

			maxX = 0;
			maxY = 0;
			float tempX, tempY;
			foreach (var item in stars)
			{
				if (!item.gameObject.activeSelf) continue;

				tempX = Mathf.Abs(item.transform.position.x - target.x);
				tempY = Mathf.Abs(item.transform.position.y - target.y);
				if (tempX > MaxShowField.x || tempY > MaxShowField.y) continue;

				if (tempX > maxX) maxX = tempX;
				if (tempY > maxY) maxY = tempY;
			}
			if (maxX == 0) maxX = MinSize.x;
			if (maxY == 0) maxY = MinSize.y;
			if (maxX/maxY > screenWDivideScreenH)
			{
				Camera.main.orthographicSize = Mathf.Lerp(Camera.main.orthographicSize, maxX * 1.1f / screenWDivideScreenH, CameraZoomSpeed);
			}
			else
			{
				Camera.main.orthographicSize = Mathf.Lerp(Camera.main.orthographicSize, maxY * 1.1f, CameraZoomSpeed);
			}

		}
	}
}
